// pages/addCom/addCom.js
const tool = require("../../utils/tool")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPage: false,
    dimension: {},
    dimensionNames: {},
    SF:'',
    XQ:'',
    LX:'',
    img:[],
    date:'',
    time:'',
    content:'',
    la:undefined,
    lo:undefined,
    showMap:false
  },

  imageClick(e){
    e = e.currentTarget.dataset.url
    wx.showActionSheet({
      itemList: ['预览','删除'],
      success:res=>{
        if(res.tapIndex==0){
          wx.previewImage({
            urls: this.data.img,
            current:e
          })
        }else{
          let re = []
          for(let i=0;i<this.data.img.length;i++){
            if(this.data.img[i]==e){
              continue
            }
            re.push(this.data.img[i])
          }
          this.setData({
            img:re
          })
        }
      }
    })
  },

  inputContent(e){
    this.setData({
      content: e.detail.value
    })
  },

  dateChange(e){
    this.setData({
      date:e.detail.value
    })
  },

  timeChange(e){
    this.setData({
      time:e.detail.value
    })
  },

  previewImageClick(e){
    e = e.currentTarget.dataset.url
    wx.previewImage({
      urls: this.data.img,
      current: e
    })
  },

  deleteImage(e){
    e = e.currentTarget.dataset.url
    let re = this.data.img
    let re1 = []
    for(let i=0;i<re.length;i++){
      if(re[i]==e){
        continue
      }else{
        re1.push(re[i])
      }
    }
    this.setData({
      img:re1
    })
  },

  async uploadFile(){
    wx.chooseImage({  
      count: 9 - this.data.img.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {  
        let tempFilePaths = res.tempFilePaths;  
        for(let i=0;i<tempFilePaths.length;i++){
          tempFilePaths[i] = await tool.comImg(tempFilePaths[i])
        }
        let re = this.data.img
        for(let i=0;i<tempFilePaths.length;i++){
          re.push(tempFilePaths[i])
        }
        console.log(123,re)
        this.setData({
          img:re
        })
      }  
    })
  },

  dimensionSelectClick(e){
    e = e.currentTarget.dataset.type
    let re = []
    for(let i=0;i<this.data.dimension[e].length;i++){
      re.push(this.data.dimension[e][i].name)
    }
    wx.showActionSheet({
      itemList: re,
      success:(e1)=>{
        switch (e) {
          case '身份':
            this.setData({
              SF:re[e1.tapIndex]
            })
            break;
          case '校区':
            this.setData({
              XQ:re[e1.tapIndex]
            })
            break;
          case '类别':
            this.setData({
              LX:re[e1.tapIndex]
            })
            break;
        }
      }
    })
  },

  dimensionSelectChange(e){
    switch (e.currentTarget.dataset.type) {
      case '身份':
        this.setData({
          SF:this.data.dimensionNames[e.currentTarget.dataset.type][parseInt(e.detail.value)]
        })
        break;
      case '校区':
        this.setData({
          XQ:this.data.dimensionNames[e.currentTarget.dataset.type][parseInt(e.detail.value)]
        })
        break;
      case '类别':
        this.setData({
          LX:this.data.dimensionNames[e.currentTarget.dataset.type][parseInt(e.detail.value)]
        })
        break;
    }
  },

  closePoi(){
    this.setData({
      la:undefined,
      lo:undefined,
      showMap:false,
    })
  },

  choosePoi(){
    wx.chooseLocation({
      success:res=>{
        this.setData({
          la:res.latitude,
          lo:res.longitude,
          showMap:true
        })
      },
      fail:res=>{
        console.log(res)
      }
    })
  },

  getCurrentPoi(){
    wx.getLocation({
      type: 'gcj02',
      success:(res)=>{
        this.setData({
          la:res.latitude,
          lo:res.longitude,
          showMap:true
        })
      },
      fail(res){
        wx.showModal({
          title: '提示',
          content: '未授权，请在设置中开启位置信息',
          showCancel: false
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    tool.setThemeColor(this)
    this.setData({
      sysImagURLPrefix:wx.getStorageSync('sysImagURLPrefix')
    })
    options = JSON.parse(options.data)
    this.setData({
      statusBarHeight: (parseInt(options.statusBarHeight.split('px')[0])).toString() + 'px',
      loginedUserInfo: options.loginedUserInfo,
      contentHeight: (parseInt(options.contentHeight.split('px')[0]) + 3).toString() + 'px'
    })
    if(this.data.loginedUserInfo.account.length>13){
      this.setData({
        SF:'老师'
      })
    }else{
      this.setData({
        SF:'学生'
      })
    }
    wx.showLoading({ mask:true,
      title: '请稍候',
    })
    let re = await tool.requestMethod("/dimension/get")
    wx.hideLoading()
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    }

    let currentTime = new Date()
    currentTime = new Date(currentTime.getTime() + 24*60*60*1000)
    let dateString = ''
    dateString += currentTime.getFullYear().toString() + '-'
    if((currentTime.getMonth() + 1)<10){
      dateString+='0'
    }
    dateString+=(currentTime.getMonth() + 1).toString()
    dateString += '-'
    if(currentTime.getDate()<10){
      dateString+='0'
    }
    dateString+=(currentTime.getDate()).toString()

    let timeString = currentTime.getHours().toString() + ':' + (currentTime.getMinutes()<10?('0' + currentTime.getMinutes().toString()):(currentTime.getMinutes().toString())) 
    
    let t = {
      类别:[],
      校区:[],
      身份:[]
    }
    for(let i=0;i<re.results['类别'].length;i++){
      t.类别.push(re.results['类别'][i].name)
    }
    for(let i=0;i<re.results['校区'].length;i++){
      t.校区.push(re.results['校区'][i].name)
    }
    for(let i=0;i<re.results['身份'].length;i++){
      t.身份.push(re.results['身份'][i].name)
    }
  
    this.setData({
      dimension: re.results,
      dimensionNames: t,
      showPage: true,
      date: dateString,
      time: timeString
    })
  },

  async submitCom(){
    if(this.data.SF==''){
      tool.showToast('请选择身份')
      return
    }
    if(this.data.XQ==''){
      tool.showToast('请选择校区')
      return
    }
    if(this.data.LX==''){
      tool.showToast('请选择类别')
      return
    }
    if(this.data.content==''){
      tool.showToast('请输入文字描述')
      return
    }
    if(this.data.img.length==0){
      tool.showToast('请上传图片')
      return
    }
    if(new Date(this.data.date + ' ' + this.data.time)<=new Date()){
      tool.showToast('处理截止时间应晚于当前时间')
      return
    }
    wx.showLoading({ mask:true,
      title: '请稍候',
    })
    let imgs = []
    for(let i=0;i<this.data.img.length;i++){
      let re = await tool.uploadFile(this.data.img[i])
      if(re){
        imgs.push(re)
      }
    }
    let re1 = await tool.requestMethod("/com/add",{
      account:this.data.loginedUserInfo.account,
      comTime:this.data.date + ' ' + this.data.time,
      content:tool.removeBreak(this.data.content),
      img:imgs,
      SF:this.data.SF,
      XQ:this.data.XQ,
      LX:this.data.LX,
      lalo:[this.data.la,this.data.lo]
    })
    wx.hideLoading()
    if(re1.status==-2){
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    }
    wx.setStorageSync('refreshComList', 'true')
    wx.navigateBack()
    wx.showToast({
      title: '巡查成功',
    })
  },

  back() {
    wx.navigateBack()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})